package com.fourthGroup.service.impl;

import com.fourthGroup.feign.OrderFeignClient;
import com.fourthGroup.service.CouponService;
import com.fourthGroup.service.TradeService;
import com.fourthGroup.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class TradeServiceImpl implements TradeService {

    @Autowired
    private CouponService couponService;
    
    @Autowired
    private OrderFeignClient orderFeignClient;

    @Override
    public Result<String> createOrderWithCoupon(Integer userId, Integer productId, Integer number, Long couponId) {
        // 生成订单号
        String orderId = UUID.randomUUID().toString().replace("-", "");
        
        // 检查并使用优惠券（实际项目中应该在订单确认后使用优惠券）
        Result<Boolean> useCouponResult = couponService.useCoupon(userId, couponId, orderId);
        if (!useCouponResult.getCode().equals(200)) {
            return Result.error(useCouponResult.getMessage());
        }
        
        // 调用订单服务应用优惠券（实际项目中应包含更多订单创建逻辑）
        Result<Double> applyCouponResult = orderFeignClient.applyCoupon(orderId, couponId);
        if (!applyCouponResult.getCode().equals(200)) {
            // 回滚优惠券使用（实际项目中应通过分布式事务处理）
            log.error("应用优惠券失败，需要回滚优惠券使用状态");
            return Result.error("创建订单失败: " + applyCouponResult.getMessage());
        }
        
        log.info("用户{}成功使用优惠券{}创建订单{}", userId, couponId, orderId);
        return Result.success(orderId);
    }
} 